package com.wholeintech.ble;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.wholeintech.zigbee.gw.DeviceManager;
import com.wholeintech.utils.CommonUtil;
import com.wholeintech.entity.DeviceDb;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.wholeintech.zigbee.gw.DeviceManager.TYPE_FRESH_AIR;
import static com.wholeintech.utils.CommonIntent.ACTION_DEV_DEVCHANAGE;
import static com.wholeintech.utils.CommonIntent.ACTION_EVENT_AIRRADIO;
import static com.wholeintech.utils.CommonIntent.ACTION_VOICE_TRIGGER;

public class AirRadioDevice {

    public static final String TAG = "AirRadioDevice";
    public static final int CO2_TYPE_POSITION = 15;
    public static final int CO2_DATA_POSITION = 18;
    public static final int TEMP_TYPE_POSITION = 23;
    public static final int TEMP_DATA_POSITION = 14;
    public static final int RH_TYPE_POSITION = 30;
    public static final int RH_DATA_POSITION = 16;
    public static final int PM25_TYPE_POSITION = 10;
    public static final int PM25_DATA_POSITION = 10;
    public static final int VOC_TYPE_POSITION = 44;
    public static final int VOC_DATA_POSITION = 20;

    private static byte[] mAirRadioBuff = new byte[100];
    private static int mAirRadioCnt = 0;

    private int type = DeviceList.TYPE_AIR_RADIO;
    private Context mContext;

    private AirRadioDevice() {
    }

    public AirRadioDevice(Context c) {
        mContext = c;
    }

    public void setSensorData(String address, byte[] data) {
        DbManager db = CommonUtil.MyDbUtils();
        address = address.replace(":", "");
        Log.e(TAG, "setSensorData mac" + address);

        try {
//            DeviceDb me = db.findFirst(Selector.from(DeviceDb.class).where("macAddr", "=", address));
            DeviceDb me = db.selector(DeviceDb.class).where("macAddr", "=", address).findFirst();
            if (me != null) {
                try {
                    String text = new String(data, "UTF-8");
                    setAirRadioData(data);
                    if (text.indexOf("Voice Trig OK", 0) != -1) {
                        //TODO

                        Intent mIntent = new Intent(ACTION_VOICE_TRIGGER);
                        mIntent.putExtra("keycode", 0);
                        mContext.sendBroadcast(mIntent);

                        Log.e(TAG, "Voice Trig OK");

                        return;
                    } else if (text.indexOf("OK \n", 0) != -1) {
                        if (getdata() == 0)
                            return;
                        me.setTEMP(getTempData() / 10);
                        me.setHumidity(getRHData());
                        me.setCO2(getCO2Data());
                        me.setVOC(getVOCData());
                        me.setStatus(DeviceManager.Dev_STATUS_eConnected);
                        if (me.getPM25() != getPm25Data()) {
                            me.setPM25(getPm25Data());
                            Intent mIntent = new Intent(ACTION_EVENT_AIRRADIO);
                            mIntent.putExtra("boxId", me.getBoxId());
                            mIntent.putExtra("deviceId", me.getDevId());
                            mIntent.putExtra("network", TYPE_FRESH_AIR);
                            mContext.sendBroadcast(mIntent);
                        }

                        //发送状态改变广播到上层
                        CommonUtil.sendBroadcastMsg(mContext,ACTION_DEV_DEVCHANAGE,me.getBoxId(),me.getDevId(),me.getType(),false,null);
                        Log.e(TAG,"sendBroadcastMsg===1");
                        db.saveOrUpdate(me);
                        Log.e(TAG, "AirRadio:" + "Temp:" + getTempData() + ", Hum:"
                                + getRHData() + ", co2:" + getCO2Data() + ", pm2.5:"
                                + getPm25Data() + ", voc:" + getVOCData());
                    }

                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                }
            }

        } catch (DbException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public void setAirRadioData(byte[] data) {
        try {
            String text = new String(data, "UTF-8");
            //mRecvText.append(text.toString()+" \t");

            if (text.indexOf("OK \n", 0) != -1) {
                //String text2=bytesToHexString(mAirRadioBuff,0x3B);
                //if(text!=null){
                //	mRecvText.append(text2.toString());
                //	mAirRadioCnt=0;
                //	mRecvText.append("\n over \n");
                //}
                mAirRadioCnt = 0;
                return;
            }

            if (data[0] == 0x68 && data[1] == 00 && data[3] == 0x68) {
                mAirRadioCnt = 0;
            }

            System.arraycopy(data, 0, mAirRadioBuff, mAirRadioCnt * 20,
                    data.length);
            mAirRadioCnt++;

            if (mAirRadioCnt > 3) {
                mAirRadioCnt = 0;
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    public byte[] getAirRadioData() {
        return mAirRadioBuff;
    }

    public int getdata() {
        if (getTempData() == -1 || getTempData() > 1000)
            return 0;
        if (getRHData() == -1 || getRHData() > 100 || getRHData() == 0)
            return 0;
        if (getPm25Data() == -1)
            return 0;
        if (getVOCData() == -1 || getVOCData() > 50)
            return 0;

        if (getCO2Data() == -1 || getCO2Data() == 0)
            return 0;

        if (getTempData() == 0 && getRHData() == 0 && getPm25Data() == 0 && getCO2Data() == 0)
            return 0;

        Log.e(TAG, "AirRadio:" + "Temp:" + getTempData() + ", Hum:"
                + getRHData() + ", co2:" + getCO2Data() + ", pm2.5:"
                + getPm25Data() + ", voc:" + getVOCData());
        return 1;
    }

    public int getCO2Data() {
        int temp = 0;
        if ((mAirRadioBuff[0] & 0x00ff) == 0x68 && (mAirRadioBuff[1] & 0x00ff) == 0x00) {
            temp = (mAirRadioBuff[CO2_DATA_POSITION] << 8) & 0xff00;
            temp = (temp | (mAirRadioBuff[CO2_DATA_POSITION + 1] & 0xff));
            return temp;
        }

        return 0x0;
    }

    public int getTempData() {
        int temp = 0;
        if ((mAirRadioBuff[0] & 0x00ff) == 0x68 && (mAirRadioBuff[1] & 0x00ff) == 0x00) {
            temp = (mAirRadioBuff[TEMP_DATA_POSITION] << 8) & 0xff00;
            temp = (temp | (mAirRadioBuff[TEMP_DATA_POSITION + 1] & 0xff));
            if (temp > 1270){
                temp = temp-65536;
            }
            return temp;
        }



        return 0;
    }

    public int getRHData() {
        int temp = 0;
        if ((mAirRadioBuff[0] & 0x00ff) == 0x68 && (mAirRadioBuff[1] & 0x00ff) == 0x00) {
            temp = (mAirRadioBuff[RH_DATA_POSITION] << 8) & 0xff00;
            temp = (temp | (mAirRadioBuff[RH_DATA_POSITION + 1] & 0xff));
            return temp;
        }

        return -1;
    }

    public int getPm25Data() {
        int temp = 0;
        if ((mAirRadioBuff[0] & 0x00ff) == 0x68 && (mAirRadioBuff[1] & 0x00ff) == 0x00) {
            temp = (mAirRadioBuff[PM25_DATA_POSITION] << 8) & 0xff00;
            temp = (temp | (mAirRadioBuff[PM25_DATA_POSITION + 1] & 0xff));
            return temp;
        }

        return -1;
    }

    public int getVOCData() {
        int temp = 0;
        if ((mAirRadioBuff[0] & 0x00ff) == 0x68 && (mAirRadioBuff[1] & 0x00ff) == 0x00) {
            temp = (mAirRadioBuff[VOC_DATA_POSITION] << 8) & 0xff00;
            temp = (temp | (mAirRadioBuff[VOC_DATA_POSITION + 1] & 0xff));
            return temp;
        }

        return -1;
    }

    private void sendBroadcastMsg(String intent, String boxId, String devId,
                                  int type) {
        Intent mIntent = new Intent(intent);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String timeStr = formatter.format(curDate);

        mIntent.putExtra("boxId", boxId);
        mIntent.putExtra("deviceId", devId);
        mIntent.putExtra("type", type);
        mIntent.putExtra("time", timeStr);

        Log.i(TAG, "sendBroadcast: " + intent + ",deviceId:" + devId);

        mContext.sendBroadcast(mIntent);
    }

}

